package com.fileshare.web;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Properties;
import java.util.Scanner;

import static com.fileshare.web.constant.CommonConstant.*;

@MapperScan("com.fileshare.web.dao")
@SpringBootApplication
@EnableTransactionManagement
public class WebApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(this.getClass());
    }

    public static void main(String[] args) {
        loadCustomEnvConfiguration();
        SpringApplication.run(WebApplication.class, args);
    }

    private static void loadCustomEnvConfiguration() {
        Properties properties = System.getProperties();
        String path = new File(EMPTY).getAbsolutePath();
        properties.put("ROOT_DIR", path);
        String resourcesDir = path + "/src/main/resources";
        String envFileName = "env.conf";
        File folder = new File(resourcesDir);
        if (folder.exists() && folder.isDirectory()) {
            File envFile = new File(resourcesDir + FORWARD_SLASH + envFileName);
            if (envFile.exists()) {
                loadConfigToEnv(properties, envFile);
            }
        }
    }

    private static void loadConfigToEnv(Properties properties, File envFile) {
        try (Scanner sc = new Scanner(envFile)) {
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                //去掉自定义注释
                if (line.startsWith("[") && line.endsWith("]")) continue;
                String[] keyAndValue = line.split(EQUAL_SIGN);
                if (keyAndValue.length >= 2) {
                    properties.put(keyAndValue[0], keyAndValue[1]);
                }
            }
        } catch (FileNotFoundException ignored) {
        }
    }
}
